package com.erp.erp_servers.Customer.imp;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.erp.erp_dao.Customer.ICustomerDAO;
import com.erp.erp_dao.Customer2.ICustomer2DAO;
import com.erp.erp_dao.Customer2Contact.ICustomer2ContactDAO;
import com.erp.erp_dao.CustomerContact.ICustomerContactDAO;
import com.erp.erp_dao.business.IExportContractDao;
import com.erp.erp_entitys.Cost.vo.QueryCostStatistics1VO;
import com.erp.erp_entitys.Customer.*;
import com.erp.erp_entitys.Customer2.Customer2Entity;
import com.erp.erp_entitys.Customer2.Customer2Example;
import com.erp.erp_entitys.Customer2Contact.Customer2ContactEntity;
import com.erp.erp_entitys.Customer2Contact.Customer2ContactExample;
import com.erp.erp_entitys.CustomerContact.CustomerContactEntity;
import com.erp.erp_entitys.CustomerContact.CustomerContactExample;
import com.erp.erp_entitys.Dictionary.DictionaryEntity;
import com.erp.erp_entitys.Email.email_custor;
import com.erp.erp_entitys.User.UserEntity;
import com.erp.erp_entitys.User.UserEntityExample;
import com.erp.erp_entitys.business.entity.ExportContractEntity;
import com.erp.erp_servers.Customer.ICustomerService;
import com.erp.erp_servers.Customer2.ICustomer2Service;
import com.erp.erp_servers.CustomerContact.ICustomerContactService;
import com.erp.erp_servers.Dictionary.IDictionary2Service;
import com.erp.erp_servers.Email.EmailService;
import com.erp.erp_servers.User.IUserService;
import com.erp.utils.DateUtils;
import com.erp.utils.StringUtil;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName ImpCustomerService
 * @Description TODO
 * @Author songjizhen
 * @Date 2020-06-29 20:05
 * @Version 1.0
 */
@Service
public class ImpCustomerService implements ICustomerService {
    @Autowired
    ICustomerDAO customerDAO;
    @Autowired
    ICustomer2DAO customer2DAO;
    @Autowired
    ICustomerContactDAO customerContactDAO;
    @Autowired
    ICustomer2ContactDAO customer2ContactDAO;
    @Autowired
    ICustomer2Service customer2Service;
    @Autowired
    EmailService emailService;
    @Autowired
    IDictionary2Service dictionary2Service;
    @Autowired
    ICustomerContactService customerContactService;
    @Autowired
    IUserService userService;
    @Autowired
    IExportContractDao exportContractDao;

    @Override
    public long countByExample(CustomerExample example) {
        return customerDAO.countByExample(example);
    }

    @Override
    public int deleteByExample(CustomerExample example) {
        return customerDAO.deleteByExample(example);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteByExample(CustomerExample example, List<Integer> ids) throws Exception {
        List<CustomerEntity> customerEntities = this.selectByExample(example);
        int num = customerDAO.deleteByExample(example);
        if(num >0 ){
            List<email_custor> email_custors=new ArrayList<>();
            //获取客户所有code
            List<String> customerCodes=new ArrayList<>();
            for(int i=0;i<customerEntities.size();i++){
                CustomerEntity ce=customerEntities.get(i);
               customerCodes.add(ce.getCode());
            }
            //获取客户联系人
            CustomerContactExample example2=new CustomerContactExample();
            CustomerContactExample.Criteria criteria = example2.createCriteria();
            criteria.andCompanyIn(customerCodes);
            List<CustomerContactEntity> customerContactEntities = customerContactDAO.selectByExample(example2);
            for(int i=0;i<customerContactEntities.size();i++){
                CustomerContactEntity cce=customerContactEntities.get(i);
                email_custor ec=new email_custor();
                ec.setOldEmail(cce.getEmail());
                ec.setId(cce.getId());
                ec.setNewEmail(cce.getEmail());
                ec.setName(cce.getName());
                ec.setStatue(0);
                ec.setHandle(2);
                ec.setCodeClass(1);
                ec.setCode(""+cce.getId());
                email_custors.add(ec);
            }
            //更新邮件模块
            boolean tf = emailService.checkUserBox(email_custors);
            if(!tf){
                throw new Exception("");
            }
        }

        return num;
    }

    @Override
    public int deleteByPrimaryKey(Integer id) {
        return customerDAO.deleteByPrimaryKey(id);
    }

    @Override
    public int insert(CustomerEntity record) {
        return customerDAO.insert(record);
    }

    @Override
    public int insertSelective(CustomerEntity record) {
        return customerDAO.insertSelective(record);
    }

    @Override
    public List<CustomerEntity> selectByExample(CustomerExample example) {
        return customerDAO.selectByExample(example);
    }

    @Override
    public List<CustomerEntity> select(CustomerEntity record) {
        return customerDAO.select(record);
    }

    /**
     * 分层获取客户
     *
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> getAllCustomer(Integer type, Integer lx ) {
        // 返回结果列表
        Map<String, Object>  resultMap=new HashMap<>();
     List<Map<String,Object>> resultList=new ArrayList<>();
        List<DictionaryEntity> value= dictionary2Service.getValue(type, lx);
        Map<String, Object> map=new HashMap<>();
        for(DictionaryEntity de:value){
            map.put(de.getCode(),de.getName());
        }

        //取所有联系人
        CustomerContactExample example2=new CustomerContactExample();
        CustomerContactExample.Criteria criteria2 = example2.createCriteria();
        List<CustomerContactEntity> customerContactEntities = customerContactService.selectByExample(example2);
        //根据客户分类获取客户信息

        for(Map.Entry<String,Object> entry:map.entrySet()){
            CustomerExample example=new CustomerExample();
            CustomerExample.Criteria criteria = example.createCriteria();
            criteria.andTypeEqualTo(entry.getKey());
            //根据分类取其下客户
            List<CustomerEntity> list= customerDAO.selectByExample(example);

            //客户分类
            Map<String,Object> mp=new HashMap<>();
            mp.put(entry.getKey(),entry.getValue());

            //客户列表

            List<Map<String,Object>>customer=new ArrayList<>();
            for(CustomerEntity ce:list){
                Map<String,Object> contactMap=new HashMap<>();
                contactMap.put(ce.getCode(),ce.getName());
                List<Map<String,Object>> contactList=new ArrayList<>();
                for(CustomerContactEntity cce:customerContactEntities){
                    if(!cce.getCompany().equals(ce.getCode())){
                        continue;
                    }
                    Map<String,Object> m=new HashMap<>();
                    m.put("name",cce.getName());
                    m.put("email",cce.getEmail());
                    m.put("id",cce.getId());
                    contactList.add(m);
                }
                contactMap.put("contact",contactList);
                customer.add(contactMap);
            }
            mp.put("customer",customer);
            resultList.add(mp);
        }
        resultMap.put("customer",resultList);
        return resultMap;
    }

    @Override
    public CustomerEntity selectByPrimaryKey(Integer id) {
        return customerDAO.selectByPrimaryKey(id);
    }

    @Override
    public int updateByExampleSelective(CustomerEntity record, CustomerExample example) {
        return customerDAO.updateByExampleSelective(record,example);
    }

    @Override
    public int updateByExample(CustomerEntity record, CustomerExample example) {
        return customerDAO.updateByExample(record,example);
    }

    @Override
    public int updateByPrimaryKeySelective(CustomerEntity record) {
        return customerDAO.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(CustomerEntity record) {
        return customerDAO.updateByPrimaryKey(record);
    }

    @Override
    public List<CustomerEntity>  selectByMap( CustomerEntity record) {
        return customerDAO.selectByMap(record);
    }
    @Override
    public List<CustomerEntity>  selectByMap2( CustomerEntity record) {
        return customerDAO.selectByMap2(record);
    }

    @Override
    public List<CustomerEntity> selectByKzt(String days, String saleman, String name,String type) {
        List<CustomerEntity> customerEntities = customerDAO.selectByKzt(days, saleman, name,type);
        return customerEntities;
    }

    /**
     * 根据Id更新流程状态
     *
     * @param id
     * @return
     */
    @Override
    public boolean updateStatus(String id,String spstatus) {
        CustomerEntity record=new CustomerEntity();
        record.setId(Integer.parseInt(id));
        record.setSpstatus(spstatus);
        int num= customerDAO.updateByPrimaryKeySelective(record);
        return num==0?false:true;
    }

    /**
     * 客户汇总、供应商汇总
     *
     * @return
     */
    @Override
    public Map<String, Object> getHZ(UserEntity user) {
        Map<String, Object> map=new HashMap<>();
        map=getCustomer(user);
        return map;
    }
    @Override
    public Map<String, Object> getHZ2(UserEntity user) {
        Map<String, Object> map=new HashMap<>();
        map=getCustomer2(user);
        return map;
    }
    /**
     * 30天、60天内未联系的客户
     *
     * @param user
     * @return
     */
    @Override
    public Map<String, Object> getHZ30And60Days(UserEntity user) {
        CustomerExample example=new  CustomerExample();
        CustomerExample.Criteria criteria = example.createCriteria();
        criteria.andSalesmanEqualTo(user.getCode());
        List<CustomerEntity> customerEntities = selectByExample(example);
        if(customerEntities.size()==0){
            return null;
        }
        List<String> list=new ArrayList<>();
        for(CustomerEntity ce:customerEntities){
            list.add(ce.getCode());
        }
        CustomerContactExample example2 =new CustomerContactExample();
        CustomerContactExample.Criteria criteria1 = example2.createCriteria();
        criteria1.andCompanyIn(list);
        List<CustomerContactEntity> customerContactEntities = customerContactService.selectByExample(example2);
        if(customerContactEntities.size()==0){
            return null;
        }
        Map<String,Object> map=new HashMap<>();
        for(CustomerContactEntity cce:customerContactEntities){
            if(map.get(cce.getCompany() )!=null){
                List<String> listMap=(List<String>)map.get(cce.getCompany());
                listMap.add(cce.getEmail());
                map.put(cce.getCompany(),listMap);
            }else{
                List<String> listMap=new ArrayList<>();
                listMap.add(cce.getEmail());
                map.put(cce.getCompany(),listMap);
            }
        }
        return map;
    }

    /**
     * 获取客户、用户、供应商信息
     *
     * @return
     */
    @Override
    public Map<String, Object> getCustomerAndUserAndSupplier() {
        Map<String, Object> map=new HashMap<>();
        map.put("user",getAllUserEmail());
        map.put("customer",getAllCustomerInfo());
        map.put("supplier",getAllSupplierInfo());
        return map;
    }

    @Override
    public int  contactCountByDays(String days) {
        int num=0;
        List<String> list = getkztCode(customerDAO.contactCountByDays(days));
         if(list.size()>0){
             num = customerDAO.updateSalesmanByCode(list.toString());
         }
        return num;
    }

    /**
     * 根据邮箱获取用户、客户、供应商信息
     *
     * @param emailList
     * @return
     */
    @Override
    public List<Map<String, Object>> getMapByEmail(List<String> emailList) {
        List<Map<String, Object>> mapByEmail = customerDAO.getMapByEmail(emailList.toString());
        return mapByEmail;
    }

    private List<Map<String,Object>> getAllCustomerInfo(){
        List<Map<String, Object>> allCustomerInfo = customerDAO.getAllCustomerInfo();
        return allCustomerInfo;
    }
    private List<Map<String,Object>> getAllSupplierInfo(){
        List<Map<String, Object>> allSupplier = customerDAO.getAllSupplier();
        return allSupplier;
    }
    private List<Map<String,Object>> getAllUserEmail(){
        List<Map<String, Object>> allUserEmail = customerDAO.getAllUserEmail();
        return allUserEmail;
    }

    /**
     * 客户汇总
     * @return
     */
    private Map<String, Object> getCustomer2(UserEntity user){
        Map<String, Object> map=new HashMap<>();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        //获取当前月第一天：
        Calendar c = Calendar.getInstance();
        c.add(Calendar.MONTH, 0);
        c.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天
        String first = format.format(c.getTime());
        //获取当前月最后一天
        Calendar ca = Calendar.getInstance();
        ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
        String last = format.format(ca.getTime());

        CustomerExample example=new  CustomerExample();
        CustomerExample.Criteria criteria = example.createCriteria();


        criteria.andCreatetimeBetween(c.getTime(),ca.getTime());
        //本月新增客户数量
       long newCustomerCount = this.countByExample(example);
        List<CustomerEntity> customerEntities = this.selectByExample(example);


        map.put("newCustomerCount",newCustomerCount);
        map.put("newCustomer",customerEntities);

        //map.put("contact30Count",customerDAO.contactCount("30"));
        map.put("contact30",getkztCode(customerDAO.contactCountByDays("30")));
        map.put("contact30Count",customerDAO.contactCount("30"));

        map.put("contact60",getkztCode(customerDAO.contactCountByDays("60")));
        map.put("contact60Count",customerDAO.contactCount("60"));
//即将被移入公共池，即85天未联系的，90天未联系的移入公共池
        map.put("contact85",getkztCode(customerDAO.contactCountByDays("85")));
        map.put("contact85Count",customerDAO.contactCount("85"));
        //供应商
        Customer2Example example2=new Customer2Example();
        Customer2Example.Criteria criteria1 = example2.createCriteria();
        criteria1.andCreatetimeBetween(c.getTime(),ca.getTime());
        //1:合作供应商-运动营养;2:合作供应商-化妆品;3: 潜在供应商-运动营养 4:潜在供应商-化妆品
        criteria1.andBusinessTypeEqualTo("1");//业务类型
        long type1= customer2Service.countByExample(example2);
         List<Customer2Entity> customer2Entities1 = customer2Service.selectByExample(example2);
        criteria1.andBusinessTypeEqualTo("2");//业务类型
        long type2= customer2Service.countByExample(example2);
         List<Customer2Entity> customer2Entities2 = customer2Service.selectByExample(example2);
        criteria1.andBusinessTypeEqualTo("3");//业务类型
        long type3= customer2Service.countByExample(example2);
          List<Customer2Entity> customer2Entities3 = customer2Service.selectByExample(example2);
        criteria1.andBusinessTypeEqualTo("4");//业务类型
        long type4= customer2Service.countByExample(example2);
        List<Customer2Entity> customer2Entities4 = customer2Service.selectByExample(example2);
        map.put("suplierType1",type1);
        map.put("suplierType2",type2);
        map.put("suplierType3",type3);
        map.put("suplierType4",type4);

        map.put("suplierType1List",getkztCode2(customer2Entities1));
        map.put("suplierType2List",getkztCode2(customer2Entities2));
        map.put("suplierType3List",getkztCode2(customer2Entities3));
        map.put("suplierType4List",getkztCode2(customer2Entities4));

        return map;
    }
    private List<String> getkztCode2(List<Customer2Entity> list){
        List<String> li=new ArrayList<>();
        for(int i=0;i<list.size();i++){
            String obj=list.get(i).getCode();
            if(StringUtils.isNotEmpty(obj)){
                li.add(obj);
            }
        }
        return li;
    }
    private List<String> getkztCode(List<CustomerEntity> list){
        List<String> li=new ArrayList<>();
        for(int i=0;i<list.size();i++){
            String obj=list.get(i).getCode();
            if(StringUtils.isNotEmpty(obj)){
                li.add(obj);
            }
        }
        return li;
    }
    private Map<String, Object> getCustomer(UserEntity user){
        Map<String, Object> map=new HashMap<>();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        //获取当前月第一天：
        Calendar c = Calendar.getInstance();
        c.add(Calendar.MONTH, 0);
        c.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天
        String first = format.format(c.getTime());
        //获取当前月最后一天
        Calendar ca = Calendar.getInstance();
        ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
        String last = format.format(ca.getTime());

        CustomerExample example=new  CustomerExample();
        CustomerExample.Criteria criteria = example.createCriteria();
        //criteria.andSalesmanEqualTo(user.getCode());

        criteria.andCreatetimeBetween(c.getTime(),ca.getTime());
        //本月新增客户数量
        long newCustomer = this.countByExample(example);


        map.put("newCustomerCount",newCustomer);

        map.put("contact30Count",customerDAO.contactCount("30"));
        map.put("contact60Count",customerDAO.contactCount("60"));
//即将被移入公共池，即85天未联系的，90天未联系的移入公共池
        map.put("contact85Count",customerDAO.contactCount("85"));
        //供应商
        Customer2Example example2=new Customer2Example();
        Customer2Example.Criteria criteria1 = example2.createCriteria();
        criteria1.andCreatetimeBetween(c.getTime(),ca.getTime());
        //1:合作供应商-运动营养;2:合作供应商-化妆品;3: 潜在供应商-运动营养 4:潜在供应商-化妆品
        criteria1.andBusinessTypeEqualTo("1");//业务类型
        long type1= customer2Service.countByExample(example2);
        // List<Customer2Entity> customer2Entities1 = customer2Service.selectByExample(example2);
        criteria1.andBusinessTypeEqualTo("2");//业务类型
        long type2= customer2Service.countByExample(example2);
        // List<Customer2Entity> customer2Entities2 = customer2Service.selectByExample(example2);
        criteria1.andBusinessTypeEqualTo("3");//业务类型
        long type3= customer2Service.countByExample(example2);
        //  List<Customer2Entity> customer2Entities3 = customer2Service.selectByExample(example2);
        criteria1.andBusinessTypeEqualTo("4");//业务类型
        long type4= customer2Service.countByExample(example2);
        // List<Customer2Entity> customer2Entities4 = customer2Service.selectByExample(example2);
        map.put("suplierType1",type1);
        map.put("suplierType2",type2);
        map.put("suplierType3",type3);
        map.put("suplierType4",type4);

        return map;
    }
    /**
     * 根据客户流程表更新供应商表审批状态
     */
    @Override
    public int updateStatusByProcessAndCustomer() {
        int num=customerDAO.updateStatusByProcessAndCustomer();
        return num;
    }

    @Override
    public CustomerEntity findCustomerByCode(String customerCode) {
        return customerDAO.findCustomerByCode(customerCode);
    }

    /**
     * 获取当前用户所管理 （及其所管理员工）的客户联系人信息
     *
     * @param user
     * @return
     */
    @Override
    public Map<String, Object> queryConTactByUserCode(UserEntity user) {
        //所管理的员工
        String userRole=user.getCustomerRole();
        String[] split = userRole.split(",");
        List<String> listUserCode=new ArrayList<>();
        String salesman=user.getCode();
        for(int i=0;i<split.length;i++){
            listUserCode.add(split[i]);
            salesman=salesman+","+split[i];
        }
        listUserCode.add(user.getCode());
        //获取当前用户所管理 到的员工
        Map<String, Object> userMap = this.getUserList(listUserCode);
        //获取业务员所属客户
        List<Map<String,Object>>  customerList=this.getCustomerMap(salesman);
       //获取客户所属联系人
        Map<String,List<Map<String,String>>> customerConTact=getCustact(customerList);
       //组装树
        Map<String,Object> tree=new HashMap<>();
        tree.put("CODE",user.getCode());
        tree.put("NAME",user.getName());

        Map<String,Object> mList=new HashMap<>();
       /* for(int i=0;i<customerList.size();i++){
            Map<String, Object> stringObjectMap = customerList.get(i);
        }*/
        for(Map.Entry<String,Object>entry:userMap.entrySet()){
            String code=entry.getKey();
            UserEntity ue=(UserEntity)entry.getValue();
            Map<String,Object> uMap=new HashMap<>();
            uMap.put("NAME",ue.getName());
            uMap.put("CODE",ue.getCode());
            for(int i=0;i<customerList.size();i++){
                Map<String, Object> cMap = customerList.get(i);
                uMap.put(cMap.get("CODE").toString(),cMap);
                cMap.put("CUSTOMERCONTACT",customerConTact.get(cMap.get("CODE")));
               /* Object customerCode=cMap.get("CODE") ;
                Object customerName=cMap.get("NAME") ;
                Object customerSalesman=cMap.get("SALESMAN") ;
                List<Map<String, String>> maps = customerConTact.get(customerCode);*/
            }
            mList.put(ue.getCode(),uMap);
        }
        tree.put("USER",mList);
        return tree;
    }

    /**
     *
     * 获取用户名称+编码
     *
     * @param customerAndEmail
     * @return
     */
    @Override
    public List<String> selectEmailCustomByDim(CustomerAndEmail customerAndEmail) {
        String type=customerAndEmail.getType();
        String name=customerAndEmail.getName();
        String code=customerAndEmail.getCode();
        CustomerExample example=new CustomerExample();
        CustomerExample.Criteria criteria = example.createCriteria();

        Customer2Example example2=new Customer2Example();
        Customer2Example.Criteria criteria2 = example2.createCriteria();
        //0是管理员，1是普通用户
        if(type.equals("1")){
            //当前登录用户及登录用户管理到用户的code，以","进行分割
            List<String> list=new ArrayList<>();
            String[] split = code.split(",");
            for(int i=0;i<split.length;i++){
                list.add(split[i]);
            }
            criteria.andSalesmanIn(list);
            criteria2.andSalesmanIn(list);
        }
        if(StringUtils.isNotEmpty(name)){
            criteria.andNameLike("%"+name+"%");
            criteria2.andNameLike("%"+name+"%");
        }
        List<CustomerEntity> customerEntities = customerDAO.selectByExample3(example);
        List<Customer2Entity> customer2Entities = customer2DAO.selectByExample(example2);

        List<String> list=new ArrayList<>();
        for(int i=0;i<customerEntities.size();i++){
            list.add(customerEntities.get(i).getName());
        }
        //供应商加进来
        for(int i=0;i<10;i++){
            Customer2Entity ce = customer2Entities.get(i);
            list.add(ce.getName()+"<"+ce.getCode()+">");
        }


        return list;
    }

    /**
     * 获取客户、联系人两级树
     *
     * @param code
     * @return
     */
    @Override
    public List<Map<String, Object>> selectEmailCustomConCateByCode(String code) {
        List<String>list=new ArrayList<>();
        String[] split = code.split(",");
        for(int i=0;i<split.length;i++){
            list.add(split[i]);
        }
        //客户
        CustomerExample example=new CustomerExample();
        CustomerExample.Criteria criteria = example.createCriteria();
        criteria.andCodeIn(list);
        List<CustomerEntity> customerEntities = customerDAO.selectByExample(example);
        //存入客户Map
        Map<String,Object> customerMap=new HashMap<>();
        for(int i=0;i<customerEntities.size();i++){
            CustomerEntity ce = customerEntities.get(i);
            customerMap.put(ce.getCode(),ce.getName());
        }
        //供应商
        Customer2Example example22=new Customer2Example();
        Customer2Example.Criteria criteria22 = example22.createCriteria();
        criteria22.andCodeIn(list);
        List<Customer2Entity> customer2Entities = customer2DAO.selectByExample(example22);
        //供应商MAP
        Map<String,Object> customer2Map=new HashMap<>();
        for(int i=0;i<customer2Entities.size();i++){
            Customer2Entity ce2 = customer2Entities.get(i);
            customerMap.put(ce2.getCode(),ce2.getName());
        }
        //客户联系人
        CustomerContactExample example2=new CustomerContactExample();
        CustomerContactExample.Criteria criteria1 = example2.createCriteria();
        criteria1.andCompanyIn(list);
        List<CustomerContactEntity> customerContactEntities = customerContactService.selectByExample(example2);
        //存入客户联系人map
        Map<String,List<Map<String,Object>>> contactMap=new HashMap<>();
        for(int i=0;i<customerContactEntities.size();i++){
            CustomerContactEntity cce = customerContactEntities.get(i);
            if(contactMap.get(cce.getCompany()) !=null){
                List<Map<String,Object>> li= contactMap.get(cce.getCompany());
                Map<String,Object>map=new HashMap<>();
                map.put("id",cce.getId());
                map.put("name",cce.getName());
                map.put("email",cce.getEmail());
                li.add(map);
            }else{
                List<Map<String,Object>> li=new ArrayList<>();
                Map<String,Object>map=new HashMap<>();
                map.put("id",cce.getId());
                map.put("name",cce.getName());
                map.put("email",cce.getEmail());
                li.add(map);
                contactMap.put(cce.getCompany(),li);
            }
        }
        //供应商联系人
        Customer2ContactExample suplierContactExample=new Customer2ContactExample();
        Customer2ContactExample.Criteria suplierContactcriteria = suplierContactExample.createCriteria();
        suplierContactcriteria.andCompanyIn(list);
        List<Customer2ContactEntity> customer2ContactEntities = customer2ContactDAO.selectByExample(suplierContactExample);
        //存入供应商联系map
        Map<String,List<Map<String,Object>>> contact2Map=new HashMap<>();
        for(int i=0;i<customer2ContactEntities.size();i++){
            Customer2ContactEntity cce = customer2ContactEntities.get(i);
            if(contactMap.get(cce.getCompany()) !=null){
                List<Map<String,Object>> li= contact2Map.get(cce.getCompany());
                Map<String,Object>map=new HashMap<>();
                map.put("id",cce.getId());
                map.put("name",cce.getName());
                map.put("email",cce.getEmail());
                li.add(map);
            }else{
                List<Map<String,Object>> li=new ArrayList<>();
                Map<String,Object>map=new HashMap<>();
                map.put("id",cce.getId());
                map.put("name",cce.getName());
                map.put("email",cce.getEmail());
                li.add(map);
                contact2Map.put(cce.getCompany(),li);
            }
        }
        //合并两个map
        customerMap.putAll(contact2Map);
        //返回值
        List<Map<String,Object>> resultList=new ArrayList<>();
        for(Map.Entry<String,Object>entry:customerMap.entrySet()){
            String key=entry.getKey();
            String value=entry.getValue().toString();
            Map<String,Object> map=new HashMap<>();
            for(Map.Entry<String,List<Map<String,Object>>>entry1:contactMap.entrySet()){
                String key1=entry1.getKey();
                if(key.equals(key1)){
                    List<Map<String, Object>> value1 = entry1.getValue();
                    map.put("list",value1);
                    break;
                }
            }
            for(Map.Entry<String,List<Map<String,Object>>>entry1:contact2Map.entrySet()){
                String key1=entry1.getKey();
                if(key.equals(key1)){
                    List<Map<String, Object>> value1 = entry1.getValue();
                    map.put("list",value1);
                    break;
                }
            }
            map.put("code",key);
            map.put("name",value);
            resultList.add(map);
        }
        return resultList;
    }

    //获取客户的联系人
    private Map<String,List<Map<String,String>>> getCustact(  List<Map<String,Object>>   list){
        List<String> listCompany=new ArrayList<>();
        //String company="";
        for(int i=0;i<list.size();i++){
            Map<String,Object> customerMap=list.get(i);
            //company=company+customerMap.get("code")+",";
            listCompany.add(customerMap.get("CODE").toString());
        }
        /*if(company.endsWith(",")){
            company=company.substring(0,company.length()-1);
        }*/
        CustomerContactExample example=new CustomerContactExample();
        CustomerContactExample.Criteria criteria = example.createCriteria();
        criteria.andCompanyIn(listCompany);
        List<CustomerContactEntity> customerContactEntities = customerContactDAO.selectByExample(example);

        Map<String,List<Map<String,String>>> map=new HashMap<>();
        for(int i=0;i<customerContactEntities.size();i++){
            CustomerContactEntity ce=customerContactEntities.get(i);
            if(null !=map.get("COMPANY")){
                String contactName=ce.getName() ;
                String email=ce.getEmail() ;
                List<Map<String,String>> listMap= map.get(ce.getCompany());
                Map<String,String> mp=new HashMap<>();
                mp.put("NAME",contactName);
                mp.put("EMAIL",email);
                listMap.add(mp);
            }else{
                String contactName=ce.getName();
                String email=ce.getEmail();
                List<Map<String,String>> listMap= new ArrayList<Map<String,String>>();
                Map<String,String> mp=new HashMap<>();
                mp.put("NAME",contactName);
                mp.put("EMAIL",email);
                listMap.add(mp);
                map.put(ce.getCompany(),listMap);
            }
        }


        return map;
    }
    //获取业务员所属客户
    private List<Map<String,Object> > getCustomerMap(String salesman){
        CustomerExample example=new CustomerExample();
        CustomerExample.Criteria criteria = example.createCriteria();
        List<String> list=new ArrayList<>();
        String[] split = salesman.split(",");
        for(int i=0;i<split.length;i++){
            list.add(split[i]);
        }
        criteria.andSalesmanIn(list);
        List<CustomerEntity> customerEntities = customerDAO.selectByExample(example);
        List<Map<String,Object>> customerBySalesman=new ArrayList<>();
        for(int i=0;i<customerEntities.size();i++){
            CustomerEntity ce=customerEntities.get(i);
            Map<String,Object> map=new HashMap<>();
            //CODE,NAME,SALESMAN
            map.put("CODE",ce.getCode());
            map.put("NAME",ce.getName());
            map.put("SALESMAN",ce.getSalesman());
            customerBySalesman.add(map);
        }
        //List<Map<String,Object>> customerBySalesman = customerDAO.getCustomerBySalesman(salesman);
        return customerBySalesman;
    }

    //获取当前用户所管理 到的员工
    private Map<String,Object> getUserList(List<String> listUserCode){

        UserEntityExample useEexample=new UserEntityExample();
        UserEntityExample.Criteria criteria = useEexample.createCriteria();
        criteria.andCodeIn(listUserCode);
        List<UserEntity> userEntities = userService.selectByExample(useEexample);
        Map<String,Object> map=new HashMap<>();
        for(int i=0;i<userEntities.size();i++){
            UserEntity userEntity = userEntities.get(i);
            map.put(userEntity.getCode(),userEntity);
        }
        return map;
    }

    /**
     * 客户信息记录--集合
     * @param req
     * @return
     */
    private  List<CustomerInformationRecordRes> customerInfoList(CustomerInformationRecordReq req){
        List<CustomerInformationRecordRes> list=customerDAO.getCustomerInfoList(req);
        for (CustomerInformationRecordRes p:list){
            String customerCode=p.getCode();
            //查询该客户是否做过外销
            List<ExportContractEntity> entityList=exportContractDao.findExportContractByParam(customerCode);
            if (CollectionUtils.isEmpty(entityList)){
                p.setIsMaker("否");
            }else {
                p.setIsMaker("是");
            }

            p.setCreateTimeDateStr(DateUtils.format(p.getCreateTimeDate(),DateUtils.DATE_PATTERN));
            p.setUpdateTimeDateStr(DateUtils.format(p.getUpdateTimeDate(),DateUtils.DATE_PATTERN));
        }
        return list;
    }

    @Override
    public PageInfo<CustomerInformationRecordRes> getCustomerInfoList(CustomerInformationRecordReq req) {
        List<CustomerInformationRecordRes> list=customerInfoList(req);
        PageInfo<CustomerInformationRecordRes> pageInfo=new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public JSONObject customerInfoListExport(CustomerInformationRecordReq req) {
        List<CustomerInformationRecordRes> list=customerInfoList(req);
        JSONObject obj = new JSONObject();
        //获取excel的title信息
        JSONArray titleList = getTitleCustomerInformationRecordInfo();
        JSONArray data = new JSONArray();
        data.add(titleList);
        if (CollectionUtils.isEmpty(list)) {
            obj.put("data", data);
            return obj;
        }
        excelCustomerInformationRecordInfoExport(data, list);
        obj.put("data", data);
        return obj;
    }
    private JSONArray getTitleCustomerInformationRecordInfo() {
        JSONArray obj = new JSONArray();
        obj.add("客户编码");
        obj.add("客户名称");
        obj.add("简称");
        obj.add("客户类型");
        obj.add("业务员");
        obj.add("客户地址");
        obj.add("等级");
        obj.add("账期");
        obj.add("信用额度");
        obj.add("国家");
        obj.add("客户来源");
        obj.add("客户属性");
        obj.add("三位简码");
        obj.add("是否下单");
        obj.add("更改日期");
        obj.add("创建日期");
        return obj;
    }
    private void excelCustomerInformationRecordInfoExport(JSONArray data, List<CustomerInformationRecordRes> list) {
        for (CustomerInformationRecordRes vo : list) {
            JSONArray infoList = new JSONArray();
            infoList.add(getNotNullOfStringInfo(vo.getCode()));
            infoList.add(getNotNullOfStringInfo(vo.getName()));
            infoList.add(getNotNullOfStringInfo(vo.getAbbreviation()));
            infoList.add(getNotNullOfStringInfo(vo.getTypeName()));
            infoList.add(getNotNullOfStringInfo(vo.getSalesmanName()));
            infoList.add(getNotNullOfStringInfo(vo.getAddress()));
            infoList.add(getNotNullOfStringInfo(vo.getLevelName()));
            infoList.add(getNotNullOfStringInfo(vo.getAccountPeriod()));
            infoList.add(getNotNullOfStringInfo(vo.getCreditLine()));
            infoList.add(getNotNullOfStringInfo(vo.getCountry()));
            infoList.add(getNotNullOfStringInfo(vo.getSourceOfCustomers()));
            infoList.add(getNotNullOfStringInfo(vo.getAttributesOfCustomers()));
            infoList.add(getNotNullOfStringInfo(vo.getShortCode()));
            infoList.add(getNotNullOfStringInfo(vo.getIsMaker()));
            infoList.add(getNotNullOfStringInfo(vo.getUpdateTimeDateStr()));
            infoList.add(getNotNullOfStringInfo(vo.getCreateTimeDateStr()));
            data.add(infoList);
        }

    }

    @Override
    public int updateCustomerSal(String salesmanCode, String code) {
        return customerDAO.updateCustomerSal(salesmanCode,code);
    }

    /**
     * 判断text是否已存在
     *
     * @param text
     * @param zd
     * @return
     */
    @Override
    public String isExist(String text, String zd,  String id) {
        String ywy="";
        if(StringUtils.isNotEmpty(id)&&id.startsWith("#")){
            ywy=id.substring(1);
        }else{
            String[] objs=id.split("#");
            if(objs.length==2){
                id=objs[0];
                ywy=objs[1];
            }
        }
        zd=zd.toLowerCase();
        String pretext="";
        if(zd.equals("name")){
            pretext="名称【"+text+"】";
        }else if (zd.equals("email")){
            pretext="邮箱【"+text+"】";
        }else{
            pretext="简称【"+text+"】";
        }
        String message ="";
        if(zd.equals("email")){
            message=customerDAO.isExistEmail(text, zd, pretext,id);
             if(message.indexOf("#")!=-1){
                 String[] split = message.split("#");
                 if(split.length==2){
                     message=split[0];
                     if(StringUtils.isNotEmpty(split[1])){
                         List<String>list=new ArrayList<>();
                         list.add(split[1]);
                         List<UserEntity> userByUserCodeList = userService.getUserByUserCodeList(list);
                         message+=userByUserCodeList.get(0).getName();
                     }
                 }else{
                     message=split[0]+"在公共客户池";
                 }
                /*

                 if(StringUtils.isNotEmpty(split[1])){
                     List<String>list=new ArrayList<>();
                     list.add(split[1]);
                     List<UserEntity> userByUserCodeList = userService.getUserByUserCodeList(list);
                     message+=userByUserCodeList.get(0).getName();
                 }else{
                     message+="在公共客户池";
                 }*/

             }


            //,
            //       ( SELECT NAME FROM USER WHERE CODE =(SELECT DISTINCT salesman FROM  customer  WHERE salesman=#{ywy})),'【',#{ywy},'】'
        }else{
            message=customerDAO.isExist(text, zd, pretext,id);
        }
        return message;
    }


    @Override
    public PageInfo<CustomerBillingPeriodRes> customerBillingPeriod(CustomerBillingPeriodReq req) {
        List<CustomerBillingPeriodRes> billingPeriodResList=customerDAO.customerBillingPeriod(req);
        for (CustomerBillingPeriodRes p:billingPeriodResList) {
            p.setCreateDateStr(DateUtils.format(p.getCreateDate(),DateUtils.DATE_PATTERN));
            p.setOrderDateStr(DateUtils.format(p.getOrderDate(),DateUtils.DATE_PATTERN));
        }
        PageInfo<CustomerBillingPeriodRes> pageInfo=new PageInfo<>(billingPeriodResList);
        return pageInfo;
    }
    /**
     * 获取String类型不为空数据
     *
     * @param value 目标数据
     * @return 不为空数据
     */
    private String getNotNullOfStringInfo(String value) {
        if (StringUtils.isEmpty(value)) {
            return "";
        } else {
            return value;
        }
    }
    /**
     * 获取BigDecimal类型不为空的数据
     *
     * @param value 目标数据
     * @return 不为空数据
     */
    private BigDecimal getNotNullOfBigDecimalInfo(BigDecimal value) {
        if (StringUtil.isNotEmpty(value)) {
            return value;
        } else {
            return new BigDecimal("0");
        }
    }
    @Override
    public JSONObject customerBillingPeriodExport(CustomerBillingPeriodReq req) {
        List<CustomerBillingPeriodRes> billingPeriodResList=customerDAO.customerBillingPeriod(req);
        for (CustomerBillingPeriodRes p:billingPeriodResList) {
            p.setCreateDateStr(DateUtils.format(p.getCreateDate(),DateUtils.DATE_PATTERN));
            p.setOrderDateStr(DateUtils.format(p.getOrderDate(),DateUtils.DATE_PATTERN));
        }
        JSONObject obj = new JSONObject();
        //获取excel的title信息
        JSONArray titleList = getTitleCollectionCustomerBillingPeriodInfo();
        JSONArray data = new JSONArray();
        data.add(titleList);
        if (CollectionUtils.isEmpty(billingPeriodResList)) {
            obj.put("data", data);
            return obj;
        }
        excelCollectionCustomerBillingPeriodInfoExport(data, billingPeriodResList);
        obj.put("data", data);
        return obj;
    }

    private JSONArray getTitleCollectionCustomerBillingPeriodInfo() {
        JSONArray obj = new JSONArray();
        obj.add("客户编码");
        obj.add("客户名称");
        obj.add("客户类型");
        obj.add("客户来源");
        obj.add("客户属性");
        obj.add("账期");
        obj.add("信用额度");
        obj.add("业务员名称");
        obj.add("创建日期");
        obj.add("成单日期");
        return obj;
    }
    private void excelCollectionCustomerBillingPeriodInfoExport(JSONArray data, List<CustomerBillingPeriodRes> list) {
        for (CustomerBillingPeriodRes vo : list) {
            JSONArray infoList = new JSONArray();
            infoList.add(getNotNullOfStringInfo(vo.getCustomerCode()));
            infoList.add(getNotNullOfStringInfo(vo.getCustomerName()));
            infoList.add(getNotNullOfStringInfo(vo.getCustomerType()));
            infoList.add(getNotNullOfStringInfo(vo.getCustomerSource()));
            infoList.add(getNotNullOfStringInfo(vo.getAttributesOfCustomers()));
            infoList.add(getNotNullOfStringInfo(vo.getPayday()));
            infoList.add(getNotNullOfStringInfo(vo.getCreditLine()));
            infoList.add(getNotNullOfStringInfo(vo.getSalesmanName()));
            infoList.add(getNotNullOfStringInfo(vo.getCreateDateStr()));
            infoList.add(getNotNullOfStringInfo(vo.getOrderDateStr()));
            data.add(infoList);
        }

    }

    @Override
    public PageInfo<CustomerOrderAndShipInfoRes> customerOrderAndShipInfo(CustomerOrderAndShipInfoReq req) {
        List<CustomerOrderAndShipInfoRes> list = customerDAO.customerOrderAndShipInfo(req);
        for (CustomerOrderAndShipInfoRes p:list){
            p.setCreateDateStr(DateUtils.format(p.getCreateDate(),DateUtils.DATE_PATTERN));
        }
        PageInfo<CustomerOrderAndShipInfoRes> pageInfo=new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public JSONObject customerOrderAndShipInfoExport(CustomerOrderAndShipInfoReq req) {
        List<CustomerOrderAndShipInfoRes> list = customerDAO.customerOrderAndShipInfo(req);
        for (CustomerOrderAndShipInfoRes p:list){
            p.setCreateDateStr(DateUtils.format(p.getCreateDate(),DateUtils.DATE_PATTERN));
        }
        JSONObject obj = new JSONObject();
        //获取excel的title信息
        JSONArray titleList = getTitleCollectionCustomerOrderAndShipInfo();
        JSONArray data = new JSONArray();
        data.add(titleList);
        if (CollectionUtils.isEmpty(list)) {
            obj.put("data", data);
            return obj;
        }
        excelCollectionCustomerOrderAndShipInfoExport(data, list);
        obj.put("data", data);
        return obj;
    }
    private JSONArray getTitleCollectionCustomerOrderAndShipInfo() {
        JSONArray obj = new JSONArray();
        obj.add("序号");
        obj.add("客户名称");
        obj.add("客户类型");
        obj.add("客户等级");
        obj.add("客户来源");
        obj.add("客户属性");
        obj.add("客户简称");
        obj.add("客户编码");
        obj.add("客户三位简码");
        obj.add("创建日期");
        obj.add("账期'");

        obj.add("出运数量");
        obj.add("出货金额");
        obj.add("结汇数量");
        obj.add("结汇金额'");
        return obj;
    }
    private void excelCollectionCustomerOrderAndShipInfoExport(JSONArray data, List<CustomerOrderAndShipInfoRes> list) {
        //出运数量
        BigDecimal carryProductNum=new BigDecimal(0);
        //出货金额
        BigDecimal shipmentAmount=new BigDecimal(0);
        //结汇数量
        BigDecimal billExchangeInfoNum=new BigDecimal(0);
        //结汇金额
        BigDecimal billExchangeInfoAmount=new BigDecimal(0);

        int num=0;
        for (CustomerOrderAndShipInfoRes vo : list) {
            JSONArray infoList = new JSONArray();
            infoList.add(++num);
            infoList.add(getNotNullOfStringInfo(vo.getCustomerName()));
            infoList.add(getNotNullOfStringInfo(vo.getCustomerType()));
            infoList.add(getNotNullOfStringInfo(vo.getLevelName()));
            infoList.add(getNotNullOfStringInfo(vo.getSourceOfCustomers()));
            infoList.add(getNotNullOfStringInfo(vo.getAttributesOfCustomers()));
            infoList.add(getNotNullOfStringInfo(vo.getAbbreviation()));
            infoList.add(getNotNullOfStringInfo(vo.getCustomerCode()));
            infoList.add(getNotNullOfStringInfo(vo.getShortCode()));
            infoList.add(getNotNullOfStringInfo(vo.getCreateDateStr()));
            infoList.add(getNotNullOfStringInfo(vo.getPayday()));

            infoList.add(getNotNullOfBigDecimalInfo(vo.getCarryProductNum()));
            infoList.add(getNotNullOfBigDecimalInfo(vo.getShipmentAmount()));
            infoList.add(getNotNullOfBigDecimalInfo(vo.getBillExchangeInfoNum()));
            infoList.add(getNotNullOfBigDecimalInfo(vo.getBillExchangeInfoAmount()));
            if(StringUtil.isNotEmpty(vo.getCarryProductNum())){
                carryProductNum = carryProductNum.add(vo.getCarryProductNum());
            }
            if(StringUtil.isNotEmpty(vo.getShipmentAmount())){
                shipmentAmount = shipmentAmount.add(vo.getShipmentAmount());
            }
            if(StringUtil.isNotEmpty(vo.getBillExchangeInfoNum())){
                billExchangeInfoNum = billExchangeInfoNum.add(vo.getBillExchangeInfoNum());
            }
            if(StringUtil.isNotEmpty(vo.getBillExchangeInfoAmount())){
                billExchangeInfoAmount = billExchangeInfoAmount.add(vo.getBillExchangeInfoAmount());
            }

            data.add(infoList);
        }
        //合计
        JSONArray infoList = new JSONArray();
        infoList.add("合计");
        infoList.add("");
        infoList.add("");
        infoList.add("");
        infoList.add("");
        infoList.add("");
        infoList.add("");
        infoList.add("");
        infoList.add("");
        infoList.add("");
        infoList.add(carryProductNum);
        infoList.add(shipmentAmount);
        infoList.add(billExchangeInfoNum);
        infoList.add(billExchangeInfoAmount);
        data.add(infoList);
    }






    @Transactional(rollbackFor = Exception.class)
    @Override
    public int potentialCustomerNotExport(String type,Integer day) {
        List<String> list= customerDAO.potentialCustomerNotExport(type,day);
        String codes= StringUtils.join(list,',');
        int num=customerDAO.updateSalesmanByCode(codes);
        return num;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int potentialCustomerLastExport(String type,Integer day) {
        List<String> list= customerDAO.potentialCustomerLastExport(type,day);
        String codes= StringUtils.join(list,',');
        int num=customerDAO.updateSalesmanByCode(codes);
        return num;
    }

    @Override
    public void updateCustomerByParam(CustomerEntity record) {
        customerDAO.updateCustomerByParam(record);
    }
}
